package cn.edu.besti.is.onlinecalculator;

import android.content.Intent;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.LinkedList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button[] buttons = new Button[23];
    private int[] ids = new int[]{
            R.id.button1_1, R.id.button1_2, R.id.button1_3, R.id.button1_4,
            R.id.button2_1, R.id.button2_2, R.id.button2_3, R.id.button2_4,
            R.id.button3_1, R.id.button3_2, R.id.button3_3, R.id.button3_4,
            R.id.button4_1, R.id.button4_2, R.id.button4_3, R.id.button4_4,
            R.id.button5_1, R.id.button5_2, R.id.button5_3, R.id.button5_4,
            R.id.button6_1, R.id.button6_2, R.id.button6_3
    };
    private TextView textView1, textView2;
    private String result = "0";
    private LinkedList<String> expr = new LinkedList<>();
    private String Mod = "Rational";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
        for (int i = 0; i < ids.length; i++) {
            buttons[i] = findViewById(ids[i]);
            buttons[i].setOnClickListener(this);
        }
        this.textView1 = findViewById(R.id.textView1);
        this.textView2 = findViewById(R.id.textView2);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        Button button = view.findViewById(id);
        String current = button.getText().toString();
        String token;
        StringBuilder expression = new StringBuilder();
        if (current.equals("CE")) {
            expr.clear();
            result = "0";
        } else if (current.equals("±")) {
            if (!expr.isEmpty()) {
                token = expr.pollLast();
                if (!calcArithmatic.isOperator(token)) {
                    if (token.contains("-")) {
                        token = token.replaceAll("-", "");
                    } else {
                        token = "-" + token;
                    }
                }
                expr.offerLast(token);
            }
        } else if (current.equals("←")) {
            expr.pollLast();
        } else if (current.equals(".") || current.equals("/")) {
            if (!expr.isEmpty()) {
                token = expr.pollLast();
                if (!calcArithmatic.isOperator(token)) {
                    if (!token.contains(current)) {
                        token += current;
                    }
                }
                expr.offerLast(token);
            }
        } else if (current.equals("=")) {
            if (!expr.isEmpty()) {
                for (String s : expr) {
                    expression.append(" ").append(s);
                }
                try {
                    MyBC myBC = new MyBC();
                    final String formula = myBC.getEquation(expression.toString().trim());
                    try {
                        result = Client.Connect(formula, Mod);
                    } catch (Exception e) {
                        Toast.makeText(this, "请检查网络连接", Toast.LENGTH_SHORT).show();
                    }
                } catch (ExprFormatException e) {
                    result = e.getMessage();
                } catch (ArithmeticException e0) {
                    result = "Divide Zero Error";
                } finally {
                    expr.clear();
                }
            }
        } else if (current.equals("√")) {
            if (Mod.equals("Rational")) {
                result = String.valueOf(Math.sqrt(Double.parseDouble(result)));
            }
        } else if (current.equals("Mr")) {
            if (result.matches("[0-9.\\-/]+")) {
                current = result;
                expr.offerLast(current);
            }
        } else if (calcArithmatic.isOperator(current)) {
            expr.offerLast(current);
        } else {
            if (!expr.isEmpty()) {
                token = expr.pollLast();
                if (calcArithmatic.isOperator(token)) {
                    expr.offerLast(token);
                    expr.offer(current);
                } else {
                    token += current;
                    expr.offerLast(token);
                }
            } else {
                expr.offerLast(current);
            }
        }
        for (String s : expr) {
            expression.append(" ").append(s);
        }
        textView1.setText(expression.toString().trim());
        textView2.setText(result);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.option1:
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                return true;
            case R.id.option2:
                expr.clear();
                result = "";
                if (item.getTitle().equals("分数模式")) {
                    buttons[21].setText("/");
                    item.setTitle("有理数模式");
                    Mod = "Fraction";
                } else {
                    buttons[21].setText(".");
                    item.setTitle("分数模式");
                    Mod = "Rational";
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
